<template>
	<Modal
		:width="600"
		:value="value"
		:title="title"
		@on-visible-change="visibleChange"
	>
		<component ref="form" :is="component" :userID="userID"></component>
		<template slot="footer">
			<div class="tc">
				<Button @click="visibleChange(false)">取消</Button>
				<Button type="primary" @click="ok">确认</Button>
			</div>
		</template>
	</Modal>
</template>
<script>
import CreateUserForm from './CreateUserForm.vue'
import UpdateUserForm from './UpdateUserForm.vue'

export default {
	name: 'UserInfoModal',
	components: {
		CreateUserForm,
		UpdateUserForm
	},
	model: {
		prop: 'value',
		event: 'visibleChange'
	},
	props: {
		value: Boolean,
		userID: {
			type: [Number, String]
		}
	},
	data() {
		return {}
	},
	computed: {
		title() {
			return this.userID ? '编辑用户' : '新增用户'
		},
		component() {
			return this.userID ? 'UpdateUserForm' : 'CreateUserForm'
		}
	},
	methods: {
		visibleChange(visible) {
			console.log(this.$refs['form'])
			!visible && this.$refs['form'].name == 'CreateUserForm' && this.$refs['form'].resetFields()
			this.$emit('visibleChange', visible)
		},
		async ok() {
			try {
				const res = await this.$refs['form'].submit()
				if (res.success) {
					this.visibleChange(false)
					this.$emit('submit')
					this.$Message.success('操作成功')
				} else {
					this.$Message.error(res.messsage)
				}
			} catch (error) {
				console.error(error)
				this.$Message.error('提交失败')
			}
		}
	}
}
</script>
